package com.example.springboot.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.pojo.vo.UserVO;
import com.example.springboot.utils.RedisConstants;
import com.example.springboot.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        String userId = null;
        if (StrUtil.isNotBlank(token)) {
            userId = JWT.decode(token).getAudience().get(0);
        }
        String redisToken = (String) redisTemplate.opsForValue().get("login:token:" + userId);

        if (!token.equals(redisToken)) {
            throw new ServiceException("401", "请登录");
        }

        //从redis中取出当前登录用户信息，存入ThreadLocal中
        UserVO userVO = (UserVO) redisTemplate.opsForValue().get(RedisConstants.LOGIN_USER_KEY);
        UserHolder.saveUser(userVO);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 如果不删除ThreadLocal中的信息，会有内存泄漏的风险
        UserHolder.removeUser();
    }
}